package com.topscore.uke.network.retrofit;

import com.topscore.uke.network.ServerUrl;
import com.topscore.utillibrary.util.MakeMD5;

import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

/**
 * Created by 71468 on 2017/9/12.
 */

public class NetClient {
    private final int TIME_OUT = 10 * 1000;
    private final String BASE_URL = ServerUrl._BaseUrl;
    private Retrofit mRetrofit;

    private NetClient() {
        mRetrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(getClient())
                .addConverterFactory(MyGsonConvertFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
    }

    private static class SingletonHolder{
        private static final NetClient INSTANCE = new NetClient();
    }

    public static NetClient getInstance(){
        return SingletonHolder.INSTANCE;
    }

    public Retrofit net(){
        return mRetrofit;
    }

    private OkHttpClient getClient() {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(TIME_OUT, TimeUnit.MILLISECONDS)
                .readTimeout(TIME_OUT, TimeUnit.MILLISECONDS)
                .addInterceptor(chain -> {
                    Request request;
                    Request.Builder builder = chain.request().newBuilder();
                    String timeStamp = String.valueOf(new Date().getTime());
                    String signal = MakeMD5.getMD5(timeStamp + "www.topscore.com");
                    builder.addHeader("requestTime", timeStamp);
                    builder.addHeader("requestSignal", signal);
                    builder.addHeader("Accept", "application/json");
                    builder.addHeader("Content-Type", "application/json");
                    request = builder.build();
                    long t1 = System.nanoTime();
                    final Logger logger = Logger.getLogger("retrofit");
                    StringBuilder sb = new StringBuilder();
                    sb.append(request.headers());
                    sb.append(request.url());
                    FormBody formBody = (FormBody) request.body();
                    if (formBody != null) {
                        sb.append("?");
                        int size = formBody.size();
                        for (int i = 0; i < size; i++) {
                            logger.info(formBody.encodedName(i) + "=" + formBody.encodedValue(i));
                            sb.append(formBody.encodedName(i));
                            sb.append("=");
                            sb.append(formBody.encodedValue(i));
                            if (i != size - 1) {
                                sb.append("&");
                            }
                        }
                    }
                    logger.info(sb.toString());
                    Response response = chain.proceed(request);
                    long t2 = System.nanoTime();
                    logger.info(String.format("Received response for %s in %.1fms%n%s",
                            response.request().url(), (t2 - t1) / 1e6d, response.headers()));
                    return response;
                })
//                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();
        return client;
    }
}
